package jdsdk

import (
	"encoding/json"
	"errors"
	"gitee.com/danlansky/go-library/httpclient"
	"log"
	"net/url"
	"time"
)

type App struct {
	SiteID      string `json:"site_id"`      //网站id
	SiteName    string `json:"site_name"`    //网站名称,可为空
	AppKey      string `json:"app_key"`      //网站对应appkey
	SecretKey   string `json:"secret_key"`   //网站对应secretkey
	AccessToken string `json:"access_token"` //授权Key
}

type JdUnionErrResp struct {
	ErrorResponse ErrorResponse `json:"error_response"`
}

type ErrorResponse struct {
	Code string `json:"code"`
	Msg  string `json:"zh_desc"`
}

const RouterURL = "https://api.jd.com/routerjson"

func (app *App) Request(method string, param interface{}) ([]byte, error) {
	// 系统参数
	params := map[string]string{}
	params["method"] = method
	params["app_key"] = app.AppKey
	params["format"] = "json"
	params["v"] = "1.0"
	params["sign_method"] = "md5"
	params["timestamp"] = time.Now().Format("2006-01-02 15:04:05")

	// 业务参数
	paramJsonStr, _ := json.Marshal(param)
	params["360buy_param_json"] = string(paramJsonStr)
	params["sign"] = GetSign(app.SecretKey, params)

	// 请求
	client := httpclient.New(httpclient.URLSetting{
		Timeout:    2 * time.Second,
		RetryCount: 0,
	})
	resp, err := client.PostForm(RouterURL, params)
	if err != nil {
		return nil, err
	}

	jdErr := JdUnionErrResp{}
	if err := json.Unmarshal(resp.Body(), &jdErr); err != nil {
		return nil, err
	}
	log.Printf("Responce:%v %v", jdErr, err)
	if jdErr.ErrorResponse.Code != "" {
		return nil, errors.New(jdErr.ErrorResponse.Msg)
	}
	return resp.Body(), nil
}

func (app *App) Values(params map[string]interface{}) url.Values {
	vals := url.Values{}
	for key, val := range params {
		vals.Add(key, GetString(val))
	}
	return vals
}
